<template>
	<el-text>如果您已绑定邮箱，并已激活，那么您将收到以下类型的邮件通知：</el-text>
	<el-form ref="formRef" :model="form" :rules="rules" label-width="30px" style="margin-top: 20px">
		<el-form-item prop="emailNotifyTypes">
			<business-code-checkbox v-model="form.emailNotifyTypes" alignment="start" code-type="emailNotifyType" direction="vertical"/>
		</el-form-item>
		<el-form-item>
			<el-button :loading="loading" icon="el-icon-CircleCheck" type="primary" @click="save">保存</el-button>
			<el-button :loading="loading" icon="el-icon-Refresh" type="primary" @click="reset">重置</el-button>
		</el-form-item>
	</el-form>
</template>

<script lang="ts" setup>

import {modifyEmailNotifyTypesApi} from '@/api/system/myself.api'
import {useUserStore} from '@/stores/modules/user.store'
import {reactive, ref} from 'vue'
import {focusFormErrorElement, getBusinessCodeData, messageSuccess} from '@/utils/commonUtil'
import type {FormInstance, FormRules} from 'element-plus'
import BusinessCodeCheckbox from '@/components/business-code-checkbox.vue'
import type {UserVo} from '@/model/user-import'

const userStore = useUserStore()

const formRef = ref<FormInstance>()

const loading = ref(false)

const form = reactive<Pick<UserVo, 'emailNotifyTypes'>>({
	emailNotifyTypes: []
})

const rules = reactive<FormRules>({
	emailNotifyTypes: [{required: false, message: '选择通知类型', trigger: 'change', type: 'array'}]
})

const save = () => {
	formRef.value!.validate(isValid => {
		if (isValid) {
			loading.value = true
			// 删掉不存在的邮件通知类型
			const businessCodeData = getBusinessCodeData('emailNotifyType')
			const codes = businessCodeData?.map(item => item.value)
			form.emailNotifyTypes = form.emailNotifyTypes.filter(item => codes?.includes(String(item)))
			modifyEmailNotifyTypesApi({userId: userStore.userId!, emailNotifyTypes: form.emailNotifyTypes}).then(response => {
				const user = response.data
				userStore.modifyUserInfo(user)
				const email = user.email
				const emailValid = user.emailValid
				if (email && emailValid === 1) {
					messageSuccess('您的设置已保存')
				} else if (email && emailValid !== 1) {
					messageSuccess('您的设置已保存（注意：邮箱未激活，请查收激活邮件或重新发送）')
				} else {
					messageSuccess('您的设置已保存（注意：您没有绑定邮箱）')
				}
			}).finally(() => {
				loading.value = false
			})
		} else {
			focusFormErrorElement()
		}
	})
}

const reset = () => {
	form.emailNotifyTypes = userStore.emailNotifyTypes
}

reset()

</script>
